<script setup>
import { ref } from 'vue'
import request from '@/api/request.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {userLoginApi} from "@/api/UserApi.js";

const form = ref({
  username: '',
  pwd: ''
})
const router = useRouter()
//登录方法
const login = () => {
  //登录校验
  formRef.value.validate(async (valid) => {
    if (valid) {
      //访问后台
      const res = await userLoginApi(form.value)
      if (res.code == 1) {
        ElMessage({
          type: "error",
          message: "用户名或密码错误"
        })
      } else {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        //改变路由地址，跳转到成功页面
        router.push('/index')
      }
    }
  })
}
//**************************表单校验*********************************************************
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 9, message: '用户名长度3-9位', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' }
    , { min: 3, max: 9, message: '密码长度3-9位', trigger: 'blur' }
  ]
}
//表单对象 dom
const formRef = ref(null)
//表单校验清空
const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <el-form ref="formRef" :model="form" label-width="auto" style="max-width: 600px" :rules="rules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码" prop="pwd">
      <el-input v-model="form.pwd" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="login">登录</el-button>
      <el-button type="primary" @click="resetForm">清空</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>
